<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" title="固定参数配置" width="32%" showFooter :closable="false"
    @ok="handleSubmit">
    <!-- 新增周期选择 -->
    <!-- <div class="period-selector">
      <label>周期设置：</label>
      <a-select v-model:value="currentCycleValue" style="width: 120px;">
        <a-select-option v-for="item in cycleOptions" :key="item.value" :value="item.value">
          {{ item.key }}
        </a-select-option>
      </a-select>
    </div> -->

    <div class="group-list">
      <div class="group" style="border: 1px dashed rgb(204 212 219 / 100%);margin: 10px 0;padding: 10px;" v-for="(item, index) in groupData"
        :key="index">
        <div class="top">
          <h4>{{ item.name }}</h4>
          <div class="price-info">
            <span class="price">最大用量：{{ item.maxUsage }}</span>
            <span class="price">分段价格：{{ item.price }}</span>
            <span v-if="item.period">周期：{{ getCycleText(item.period) }}</span>
          </div>
        </div>
        <div class="group-content">
      
          <div class="operate">
            <!-- <span class="link" @click="() => handleAddTime(index)">添加用量</span> -->
            <a-divider type="vertical" />
            <span class="link" @click="() => handleEditGroup(item, index)">编辑分段</span>
            <a-divider type="vertical" />
            <a-popconfirm title="确认删除吗？" ok-text="确定" cancel-text="取消" @confirm="() => handleDeleteGroup(item, index)">
              <span class="link">删除分段</span>
            </a-popconfirm>
          </div>
        </div>
      </div>
    </div>
    <div class="center-box">
      <a-button @click="handleCreateGroup" type="primary" :icon="h(PlusOutlined)">新增分段</a-button>
    </div>
    <ModalAddGroup2 @register="registerModal" @success="handleAddGroupSuccess" />
    <ModalAddTime @register="registerTimeModal" @success="handleAddTimeSuccess" />
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { ref, reactive, h, onMounted } from 'vue'
import ModalAddGroup2 from './ModalAddGroup2.vue'
import ModalAddTime from './ModalAddTime.vue'
import { useModal } from '@/components/Modal'
import { createPrompt } from '@/components/Prompt'
import { PlusOutlined } from '@ant-design/icons-vue'
import { buildUUID } from '@/utils/uuid'
import message from '@/views/form-design/utils/message'
import dayjs from 'dayjs'
import { addSettingPriceDetail2, getSettingPriceDetail2, deleteRecordPrice2 } from '@/api/sys/energyUnitPrice'

defineOptions({ name: 'DrawerSetting' })

const isUpdate = ref(false)
const rowId = ref()
const groupData = ref([])
const energyPriceId = ref()
const cycleOptions = ref([
  { key: '每单位用量/周期', value: 'DEFAULT' },
  { key: '每小时/周期', value: 'HOUR' },
  { key: '每天/周期', value: 'DAY' },
  { key: '每月/周期', value: 'MONTH' },
  { key: '每年/周期', value: 'YEAR' }
])
const currentCycleValue = ref('') // 默认选中每小时/周期

const [registerModal, { openModal: openModalGroup }] = useModal()
const [registerTimeModal, { openModal: openModalTime }] = useModal()

const [registerDrawer, { setDrawerProps, closeDrawer, changeLoading }] = useDrawerInner(
  async (data) => {
    const id = data.record.id
    energyPriceId.value = id
    changeLoading(true)
    const res = await getSettingPriceDetail2({ energyPriceId: id })
    changeLoading(false)

    // 处理返回数据，确保每个项都有times数组
    groupData.value = res.map(item => ({
      ...item,
      times: item.times || [] // 确保有times数组
    }))

    // 设置当前周期
    if (res && res.length > 0) {
      const firstGroupCycle = res[0].period || 'HOUR'
      currentCycleValue.value = firstGroupCycle
    }
  },
)

const formatTime = (time) => {
  const [hours, minutes] = time.split(':').map(Number)
  const date = dayjs().hour(hours).minute(minutes)
  return dayjs(date).format('HH:mm')
}

// 根据value获取周期文本
const getCycleText = (value) => {
  const period = cycleOptions.value.find(item => item.value === value)
  return period ? period.key : value
}

const handleCreateGroup = () => {
  openModalGroup(true, { isUpdate: false, groupData: groupData.value, period: currentCycleValue.value })
}

const handleEditGroup = (data, index) => {
  openModalGroup(true, {
    isUpdate: true,
    data,
    index,
    groupData: groupData.value,
    period: data.period || currentCycleValue.value
  })
}

// 删除分段
const handleDeleteGroup = (item, index) => {

  deleteRecordPrice2(item.id).then(res => {
    message.success('删除成功')
    groupData.value.splice(index, 1)
  })


}

const handleAddTime = (groupIndex) => {
  openModalTime(true, {
    isUpdate: false,
    groupIndex,
    timeIndex: groupData.value[groupIndex].times.length,
    period: groupData.value[groupIndex].period || currentCycleValue.value
  })
}

// 编辑用量
const handleEditTime = (time, groupIndex, timeIndex) => {
  openModalTime(true, {
    isUpdate: true,
    data: time,
    groupIndex,
    timeIndex,
    period: groupData.value[groupIndex].period || currentCycleValue.value
  })
}

// 删除用量
const handleDeleteTime = (groupIndex, timeIndex) => {
  groupData.value[groupIndex].times.splice(timeIndex, 1)
  message.success('删除成功')
}

// 添加分段
const handleAddGroupSuccess = ({ isUpdate, data: { values, groupIndex, period } }) => {
  if (isUpdate) {
    // 更新周期
    groupData.value[groupIndex].period = period
    Object.assign(groupData.value[groupIndex], values)
  } else {
    groupData.value.push({ ...values, energyPriceId: energyPriceId.value, times: [], period })
  }
  // 更新当前周期值
  currentCycleValue.value = period;
}


const handleAddTimeSuccess = ({ isUpdate, values, groupIndex, timeIndex, period }) => {
  if (isUpdate) {
    groupData.value[groupIndex].period = period
    groupData.value[groupIndex].times.splice(timeIndex, 1, values)
  } else {
    groupData.value[groupIndex].period = period
    groupData.value[groupIndex].times.push(values)
  }
}

const handleSubmit = () => {
  // 检查是否有分组数据
  if (!groupData.value || groupData.value.length === 0) {
    message.warning('请至少添加一个分段')
    return
  }

  const data = groupData.value.map((item) => ({
    ...item,
    times: item.times || [], // 确保有times数组
    // period: item.period || currentCycleValue.value // 提交时不需要period字段
  }))

  addSettingPriceDetail2(data).then((res) => {
    message.success('配置成功')
    closeDrawer()
  }).catch(error => {
    message.error('配置失败: ' + error.message)
  })
}
</script>

<style lang="scss" scoped>
.group-list {
  .link {
    color: #0067cc;
    font-size: 12px;
    cursor: pointer;
  }

  .top {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    h4 {
      position: relative;
      flex: 1;
      margin: 0;
      color: #181818;

      &::before {
        content: '';
        position: absolute;
        top: 50%;
        left: -16px;
        width: 4px;
        height: 12px;
        transform: translateY(-50%);
        background: #939393;
      }
    }
  }

  .price-info {
    display: flex;
    align-items: center;

    .price {
      margin-right: 16px;
    }
  }

  .group-content {
    .time-list {
      border: 1px solid #ccd4db;

      &.empty {
        height: 24px;
        border: 1px dashed rgb(204 212 219 / 100%);
      }

      .time {
        display: flex;
        align-items: center;
        height: 24px;
        padding: 0 12px;
        background: rgb(0 103 204 / 10%);
        color: #666;
        font-size: 12px;

        &:not(:last-child) {
          border-bottom: 1px solid #ccd4db;
        }

        .date {
          flex: 1;
        }
      }
    }

    .operate {
      margin: 8px 0;
    }
  }
}

.center-box {
  margin-top: 12px;
  padding-top: 12px;
  /* border-top: 1px dashed #ccd4db; */
  text-align: center;
}

/* 新增周期选择样式 */
.period-selector {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  font-size: 14px;

  label {
    margin-right: 8px;
    color: #333;
  }
}
</style>